# -*- coding: UTF-8 -*-
"""
__Project__:
__IDE__: PyCharm
__Author__: Achen, email to ***
__CreateDate__: 2024/5/11 13:21
__Desc__:通过飞书机器人推送消息
"""

import json
import time
import requests
import hmac
import hashlib
import base64
from typing import Optional, Union


class FeiShuMSG:
    def __init__(self, token: str, text: Union[str, dict], secret: Optional[str] = None):
        self.token = token
        self.secret = secret  # 默认None,所以没有签名时无需传参
        self.text = text
        self.msg = self.prepare_message()

    def send_msg_info(self):
        """
        main
        """
        if self.token == "":
            raise ValueError("token is none")
        if self.secret is not None:
            self.gen_sign()

        self.send_msg()

    def gen_sign(self):
        """
        签名加密
        """
        t_stamp = str(round(time.time()))
        sign_s = f'{t_stamp}\n{self.secret}'
        hmac_sign = hmac.new(sign_s.encode("utf-8"), digestmod=hashlib.sha256).digest()
        sign_bs = base64.b64encode(hmac_sign).decode('utf-8')
        self.msg["timestamp"] = t_stamp
        self.msg["sign"] = sign_bs

    def prepare_message(self):
        """
        处理消息类型
        """
        if isinstance(self.text, str):
            # 纯文本
            return {
                "msg_type": "text",
                "content": {
                    "text": self.text
                }
            }
        elif isinstance(self.text, dict):
            # TODO:富文本消息格式化 飞书baseline:https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
            return self.text
        else:
            raise ValueError("text must is str or dict")

    def send_msg(self):
        """
        send post request
        """
        headers = {
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
            'Content-Type': 'application/json'
        }
        self.msg = json.dumps(self.msg)
        self.msg = bytes(self.msg, "utf8")
        try:
            requests.post(self.token, data=self.msg, headers=headers)
        except requests.RequestException as e:
            raise e


if __name__ == '__main__':
    webhook = f'https://open.feishu.cn/open-apis/bot/v2/hook/82a9207f-79d2-4390-a82e-d4e3c3540509'
    secrets = f"ZRHiGlHCp3W******"  # 签名密钥 没有无需传参
    message_text = "test"  # 推送消息，纯文本为字符串，富文本格式见飞书开发者社区

    feishu = FeiShuMSG(token=webhook, secret=secrets, text=message_text)
    # feishu = FeiShuMSG(token=webhook, text=message_text)
    feishu.send_msg_info()